<?php

namespace backend\controllers;

use app\models\AsrCallClassify;
use app\models\CrmSystemYgxx;
use app\models\CrmSystemYgxx_;
use app\models\User;
use backend\models\ResetPasswordForm;
use common\models\SignupForm;
use common\models\SiteloginForm;
use Yii;
use yii\filters\AccessControl;
use yii\filters\Cors;
use yii\filters\VerbFilter;
use yii\web\Controller;

/**
 * Site controller
 */
class SiteController extends Controller
{
    /**
     *
     * {@inheritdoc}
     *
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => [
                            'login',
                            'signup',
                            'error'
                        ],
                        'allow' => true
                    ],
                    [
                        'actions' => [
                            'logout',
                            'index'
                        ],
                        'allow' => true,
                        'roles' => [
                            '@'
                        ]
                    ]
                ]
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => [
                        'post'
                    ]
                ]
            ],
            'corsFilter' => [
                'class' => Cors::className(),
                'cors' => [
                    'Origin' => ['*'],
                    'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
                    'Access-Control-Request-Headers' => ['*'],
                    'Access-Control-Allow-Origin' => [''.\Yii::$app->components['allowOutHttp']],
                    'Access-Control-Allow-Credentials' => true,
                    'Access-Control-Max-Age' => 86400,
                    'Access-Control-Expose-Headers' => [],
                ],
            ],
        ];
    }

    public function beforeAction($action)
    {
        date_default_timezone_set('PRC');//设置时间时区为中国
        header("Content-type:application/x-www-form-urlencoded text/html; charset=utf-8");//设置格式为utf-8
        header('Access-Control-Allow-Origin:'.\Yii::$app->components['allowOutHttp']);
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
        header('Access-Control-Allow-Headers:X-Requested-With, origin, content-type, accept');
        header('Access-Control-Allow-Credentials: true');
        return true;
    }

    /**
     *
     * {@inheritdoc}
     *
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction'
            ]
        ];
    }

    /**
     * Displays homepage.
     * 登录
     * @return string
     */
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup()
    {
        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                if (Yii::$app->getUser()->login($user)) {
                    Yii::$app->session->setFlash('success', '注册用户成功');
                    return $this->goHome();
                }
            }
        }

        return $this->render('signup', [
            'model' => $model,
        ]);
    }

    /**
     * Signs user up.
     * @return mixed
     */
    public function actionFrontSignup()
    {
        $model = new SignupForm();
        $data = [];
        $this->actionFrontCsrfToken();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                $data = $user;
                $success = 1;
            }else{
                $temp = $model->getErrors();
                foreach ($temp as $k=>$v){
                    $data[] = $v[0];
                }
                $success = 0;
            }
        }
        $res['data'] = $data;
        $res['res'] = $success;
        return json_encode($res);
    }

    /**
     * 前端的 拿到登陆用的token
     * @return boolean
     */
    public function actionFrontCsrfToken()
    {
        $request = \Yii::$app->getRequest();
        if ($request->enableCsrfCookie || $this->enableSession) {
            return $_POST[\Yii::$app->components['request']['csrfParam']] = $request->getCsrfToken(true);
        }
    }


    /**
     * Login action.
     *
     * @return string
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new SiteloginForm ();
        //用来保存用户名以及密码的记住信息
        $cache = Yii::$app->cache;
        $rememberMe = $cache->get("remenberMe");
        $model->rememberMe = $rememberMe;
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            $model->password = '';

            return $this->render('login', [
                'model' => $model
            ]);
        }
    }

    /**
     * Logout action.
     *
     * @return string
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();
        //清除cookie以防止不同胡浏览器出现兼容问题无法退出的问题
        Yii::$app->response->cookies->remove('_identity-backend');
        return $this->goHome();
    }

    /**
     * 前端的登陆控制器方法
     *
     * @return boolean
     */
    public function actionFrontLogin()
    {
        $_POST['_csrf-backend'] =  $this->actionFrontCsrfToken();
        $model = new SiteloginForm ();
        //用来保存用户名以 q及密码的记住信息
        $rememberMe = $_POST['SiteloginForm']['rememberMe'];
        $model->rememberMe = $rememberMe;
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            $userM = new User();
            $user = $userM->find()
                ->select("y.*,user.username as username_,user.id as id_,user.auth_key")
                ->leftJoin('crm_system_ygxx as y','y.user_id=user.id')
                ->where('user.id='.Yii::$app->user->id)
                ->asArray()
                ->one();
            $data['user'] = $user['username_'];
            $data['yggh'] = isset($user['yggh'])?$user['yggh']:'';
            $data['ygmc'] = isset($user['ygmc'])?$user['ygmc']:'';
            $data['zuoxi'] = isset($user['zxhm'])?$user['zxhm']:'';
            $data['dlxl_'] = isset($user['dlxl_'])?$user['dlxl_']:'';
            $data['allData'] = $user;
            $data['token'] = isset($user['auth_key'])?$user['auth_key']:'';
            $data['rememberMe'] = $rememberMe;
            $data['gsid'] = $user['id_'];
            $final['data'] = $data;
            $final['res'] = 1;
            return json_encode($final);
        } else {
            $err = [];
            foreach ($model->getErrors() as $k=>$v){
                $err[] = $v[0];
            }
            $final['data'] = $err;
            $final['res'] = 0;
            return json_encode($final);
        }
    }

    /**
     * 前端的 登出系统
     *
     * @return string
     */
    public function actionFrontLogout()
    {
        Yii::$app->user->logout();
        //清除cookie以防止不同浏览器出现兼容问题无法退出的问题
        Yii::$app->response->cookies->remove('_identity-backend');
        return true;
    }

    /**
     * Logout action.
     *
     * @return string
     */
    public function actionUser()
    {
        return $this->render("user");
    }


    /**
     * Resets password.
     *
     * @param string $token
     * @return mixed
     * @throws BadRequestHttpException
     */
    public function actionResetPassword()
    {
        try {
            $passwordResetRequestForm = new \app\models\PasswordResetRequestForm();
            $passwordResetRequestForm->email = Yii::$app->user->identity->email;
            $token =  $passwordResetRequestForm->sendEmail();
            $model = new ResetPasswordForm($token);
        } catch (\HttpInvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', '新密码修改成功');

            return $this->goHome();
        }

        return $this->render('resetPassword', [
            'model' => $model,
        ]);
    }


    /**
     * 保存用户名数据
     */
    public function actionSaves(){
        $res = [];
        $user = $_POST['user'];
        $model = new SiteloginForm();
        $data = '';
        if (is_set($user,'oldpassword')=="" && is_set($user,'password')=="" ){//没有输入新旧密码
            $transaction = \Yii::$app->getDb()->beginTransaction();
            if ($user['oldUsername']==$user['username']){
                $res_ = true;
            }else{
                $one = User::findOne(['username'=>$user['oldUsername']]);
                $res_ = $one->updateAttributes(['username'=>$user['username']]);
            }
            $model = new CrmSystemYgxx_();
            $yg = $model->find()->where(['username'=>$user['oldUsername']])->one();//保存员工信息
            $post['CrmSystemYgxx_']['zxhm'] = $user['zuoxi'];
            $post['CrmSystemYgxx_']['username'] = $user['username'];
            if ($yg->load($post) && $yg->validate()){
                $res1 = $yg->update();
            }else{
                $res1 = false;
            }
            if ($res_&&$res1){
                $transaction->commit();
                $res = 1;
            }else{
                $res = 0;
                $transaction->rollBack();
                $data = array_values($yg->getErrors());
            }
        } else {
            $model->username = $_POST['user']['username'];
            $model->password = $_POST['user']['oldpassword'];
            if ($_POST['user']['password']==""){
                $res['data'] =  "新密码不能为空";
                $res['res'] =  0;
                return json_encode($res);
            }
            if ($_POST['user']['oldpassword']==""){
                $res['data'] =  "旧密码不能为空";
                $res['res'] =  0;
                return json_encode($res);
            }
            if ($model->login()) {//首先验证用户名与密码是否正确
                $userModel = User::findOne(['username'=>$user['username']]);
                $userModel->updateAttributes(['zuoxi'=>$user['zuoxi'],'username'=>$user['username']]);
                try {//更新密码
                    $passwordResetRequestForm = new \app\models\PasswordResetRequestForm();
                    $passwordResetRequestForm->email = Yii::$app->user->identity->email;
                    $token =  $passwordResetRequestForm->sendEmail();
                    $model = new ResetPasswordForm($token);
                } catch (\HttpInvalidParamException $e) {
                    throw new BadRequestHttpException($e->getMessage());
                }
                $model->password = $user['password'];
                if ($model->validate() && $model->resetPassword()) {
                    $res =  1;
                }else{
                    $res =  0;
                    $data =  "密码修改失败";
                }
            }else{
                $data =  "用户名或密码错误";
                $res =  0;
            }
        }
        $final['data'] = $data;
        $final['res'] = $res;
        return json_encode($final);
    }

    /**
     * 保存用户名数据
     */
    public function actionSave(){
        $res = [];
        $user = $_POST['user'];
        $model = new SiteloginForm();
        $data = '';
        if (is_set($user,'password')=="" ){//没有输入新旧密码
            $one = User::findOne(['username'=>$user['oldUsername']]);
            if ($one){
                $res = $one->updateAttributes(['zuoxi'=>$user['zuoxi'],'username'=>$user['username']]);
                if ($res){
                    $res = 1;
                }else{
                    $res = 0;
                    $data =  "更新失败";
                }
            }
        } else {
            $model->username = $_POST['user']['username'];
            if ($_POST['user']['password']==""){
                $res['data'] =  "新密码不能为空";
                $res['res'] =  0;
                return json_encode($res);
            }
            $userModel = User::findOne(['username'=>$user['username']]);
            $userModel->updateAttributes(['username'=>$user['username'],'email'=>$user['email']]);
            try {//更新密码
                $passwordResetRequestForm = new \app\models\PasswordResetRequestForm();
                $passwordResetRequestForm->email = Yii::$app->user->identity->email;
                $token =  $passwordResetRequestForm->sendEmail();
                $model = new ResetPasswordForm($token);
            } catch (\HttpInvalidParamException $e) {
                throw new BadRequestHttpException($e->getMessage());
            }
            $model->password = $user['password'];
            if ($model->validate() && $model->resetPassword()) {
                $data = '修改成功！';
                $res =  1;
            }else{
                $res =  0;
                $data =  "密码修改失败！";
            }
        }
        $final['data'] = $data;
        $final['res'] = $res;
        return json_encode($final);
    }

}
